<template>
  <div class="chat-groups-page">
    <!-- 搜索表单 -->
    <el-card class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="搜索关键词">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入群名称或群公告"
            clearable
            style="width: 250px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 群聊列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>群聊列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleCreate">
              <el-icon><Plus /></el-icon>
              新增群聊
            </el-button>
            <el-button @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="chatGroupList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column label="群头像" width="80">
          <template #default="{ row }">
            <el-avatar
              :src="row.group_avatar"
              :size="40"
            >
              {{ row.group_name?.charAt(0) || '群' }}
            </el-avatar>
          </template>
        </el-table-column>

        <el-table-column prop="group_name" label="群名称" min-width="150" />

        <el-table-column prop="description" label="群公告" min-width="200">
          <template #default="{ row }">
            <div class="description-cell">
              {{ row.description || '暂无公告' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="member_count" label="成员数量" width="100">
          <template #default="{ row }">
            {{ row.member_count || 0 }}
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="360" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="handleEditAnnouncement(row)"
            >
              编辑公告
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="handleViewMessages(row)"
            >
              查看消息
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑群聊对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="群名称" prop="group_name">
          <el-input
            v-model="formData.group_name"
            placeholder="请输入群名称"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="群头像" prop="group_avatar">
          <el-input
            v-model="formData.group_avatar"
            placeholder="请输入群头像URL"
            maxlength="512"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="群公告" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入群公告"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 群聊详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="群聊详情"
      width="800px"
    >
      <div v-if="currentChatGroup" class="chat-group-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="群聊ID">
            {{ currentChatGroup.id }}
          </el-descriptions-item>
          <el-descriptions-item label="群名称">
            {{ currentChatGroup.group_name }}
          </el-descriptions-item>
          <el-descriptions-item label="群头像">
            <el-avatar
              v-if="currentChatGroup.group_avatar"
              :src="currentChatGroup.group_avatar"
              :size="40"
            />
            <span v-else>暂无头像</span>
          </el-descriptions-item>
          <el-descriptions-item label="成员数量">
            {{ currentChatGroup.member_count || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatDate(currentChatGroup.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="群公告" :span="2">
            <div class="announcement-content">
              {{ currentChatGroup.description || '暂无公告' }}
            </div>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 群成员列表 -->
        <div v-if="currentChatGroup.members && currentChatGroup.members.length > 0" class="members-section">
          <h4>群成员列表</h4>
          <el-table :data="currentChatGroup.members" style="width: 100%">
            <el-table-column prop="user_id" label="用户ID" width="100" />
            <el-table-column prop="nickname" label="昵称" min-width="120">
              <template #default="{ row }">
                {{ row.nickname || '未设置' }}
              </template>
            </el-table-column>
            <el-table-column prop="joined_at" label="加入时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.joined_at) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 群公告编辑对话框 -->
    <el-dialog
      v-model="announcementDialogVisible"
      title="编辑群公告"
      width="800px"
      @close="handleAnnouncementDialogClose"
    >
      <div class="announcement-editor">
        <div class="editor-section">
          <h4>编辑公告内容</h4>
          <el-input
            v-model="announcementData.description"
            type="textarea"
            :rows="8"
            placeholder="请输入群公告内容..."
            maxlength="2000"
            show-word-limit
            class="announcement-textarea"
          />

          <div class="editor-toolbar">
            <el-button size="small" @click="insertTemplate('欢迎加入群聊')">
              插入欢迎语
            </el-button>
            <el-button size="small" @click="insertTemplate('群规则：\n1. 请文明聊天\n2. 禁止发送广告\n3. 尊重他人')">
              插入群规则
            </el-button>
            <el-button size="small" @click="insertTemplate('联系管理员：')">
              插入联系方式
            </el-button>
            <el-button size="small" @click="clearAnnouncement">
              清空内容
            </el-button>
          </div>
        </div>

        <div class="preview-section">
          <h4>实时预览</h4>
          <div class="announcement-preview">
            <div v-if="announcementData.description" class="preview-content">
              {{ announcementData.description }}
            </div>
            <div v-else class="preview-placeholder">
              暂无公告内容
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="announcementDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAnnouncementSubmit" :loading="submitting">
            保存公告
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 群聊消息管理对话框 -->
    <el-dialog
      v-model="messagesDialogVisible"
      :title="`群聊消息管理 - ${currentGroupForMessages?.group_name || ''}`"
      width="1200px"
      @close="handleMessagesDialogClose"
    >
      <div class="messages-management">
        <!-- 搜索和筛选 -->
        <el-card class="search-section">
          <el-form :model="messageSearchForm" inline>
            <el-form-item label="消息类型">
              <el-select v-model="messageSearchForm.messageType" placeholder="请选择消息类型" clearable>
                <el-option label="文本消息" value="text" />
                <el-option label="图片消息" value="image" />
                <el-option label="系统消息" value="system" />
                <el-option label="需求卡片" value="demand_card" />
              </el-select>
            </el-form-item>

            <el-form-item label="搜索内容">
              <el-input
                v-model="messageSearchForm.search"
                placeholder="请输入消息内容关键词"
                clearable
                style="width: 200px"
              />
            </el-form-item>

            <el-form-item label="发送者ID">
              <el-input
                v-model="messageSearchForm.senderId"
                placeholder="请输入发送者ID"
                clearable
                style="width: 150px"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleMessageSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleMessageReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 消息统计 -->
        <el-card class="stats-section">
          <div class="stats-content">
            <div class="stat-item">
              <span class="stat-label">总消息数：</span>
              <span class="stat-value">{{ messageStats.total || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">今日消息：</span>
              <span class="stat-value">{{ messageStats.today || 0 }}</span>
            </div>
            <div v-if="messageStats.byType" class="stat-item">
              <span class="stat-label">类型分布：</span>
              <span class="stat-value">
                文本({{ messageStats.byType.text || 0 }})
                图片({{ messageStats.byType.image || 0 }})
                系统({{ messageStats.byType.system || 0 }})
                需求卡片({{ messageStats.byType.demand_card || 0 }})
              </span>
            </div>
          </div>
        </el-card>

        <!-- 消息列表 -->
        <el-card>
          <template #header>
            <div class="card-header">
              <span>消息列表</span>
              <div class="header-actions">
                <el-button
                  type="danger"
                  :disabled="selectedMessages.length === 0"
                  @click="handleBatchDeleteMessages"
                >
                  <el-icon><Delete /></el-icon>
                  批量删除 ({{ selectedMessages.length }})
                </el-button>
                <el-button @click="handleRefreshMessages">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </div>
          </template>

          <el-table
            v-loading="messagesLoading"
            :data="messagesList"
            stripe
            style="width: 100%"
            @selection-change="handleMessageSelectionChange"
          >
            <el-table-column type="selection" width="55" />

            <el-table-column prop="id" label="消息ID" width="120" />

            <el-table-column label="发送者" width="150">
              <template #default="{ row }">
                <div class="sender-info">
                  <el-avatar
                    v-if="row.sender?.avatar_url"
                    :src="row.sender.avatar_url"
                    :size="30"
                  />
                  <div class="sender-details">
                    <div class="sender-name">{{ row.sender?.nickname || '未知用户' }}</div>
                    <div class="sender-id">ID: {{ row.sender_id }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="message_type" label="消息类型" width="100">
              <template #default="{ row }">
                <el-tag
                  :type="getMessageTypeTagType(row.message_type)"
                  size="small"
                >
                  {{ getMessageTypeText(row.message_type) }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="content" label="消息内容" min-width="300">
              <template #default="{ row }">
                <div class="message-content">
                  {{ row.content }}
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="created_at" label="发送时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.created_at) }}
              </template>
            </el-table-column>

            <el-table-column label="操作" width="160" fixed="right">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleViewMessageDetail(row)"
                >
                  查看
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDeleteMessage(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="messagePagination.page"
              v-model:page-size="messagePagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="messagePagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleMessageSizeChange"
              @current-change="handleMessageCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </el-dialog>

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="messageDetailDialogVisible"
      title="消息详情"
      width="800px"
      @close="handleMessageDetailDialogClose"
    >
      <div v-if="currentMessageDetail" class="message-detail">
        <!-- 消息基本信息 -->
        <el-descriptions :column="2" border>
          <el-descriptions-item label="消息ID">
            {{ currentMessageDetail.id }}
          </el-descriptions-item>
          <el-descriptions-item label="消息类型">
            <el-tag
              :type="getMessageTypeTagType(currentMessageDetail.message_type)"
              size="small"
            >
              {{ getMessageTypeText(currentMessageDetail.message_type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="发送者">
            <div class="sender-info-detail">
              <el-avatar
                v-if="currentMessageDetail.sender?.avatar_url"
                :src="currentMessageDetail.sender.avatar_url"
                :size="40"
              />
              <div class="sender-details-detail">
                <div class="sender-name">{{ currentMessageDetail.sender?.nickname || '未知用户' }}</div>
                <div class="sender-id">ID: {{ currentMessageDetail.sender_id }}</div>
                <div v-if="currentMessageDetail.sender?.phone_number" class="sender-phone">
                  手机: {{ currentMessageDetail.sender.phone_number }}
                </div>
              </div>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="发送时间">
            {{ formatDate(currentMessageDetail.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="所属群聊" :span="2">
            {{ currentMessageDetail.group?.group_name || '未知群聊' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 消息内容 -->
        <el-card class="message-content-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>消息内容</span>
              <el-button
                type="primary"
                size="small"
                @click="copyMessageContent"
              >
                <el-icon><DocumentCopy /></el-icon>
                复制内容
              </el-button>
            </div>
          </template>

          <div class="message-content-full">
            <pre>{{ currentMessageDetail.content }}</pre>
          </div>
        </el-card>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="messageDetailDialogVisible = false">关闭</el-button>
          <el-button
            type="danger"
            @click="handleDeleteMessageFromDetail"
          >
            删除此消息
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Search, Refresh, Plus, Delete, DocumentCopy } from '@element-plus/icons-vue'
import {
  chatGroupApi,
  messageApi,
  type ChatGroup,
  type ChatGroupListParams,
  type CreateChatGroupParams,
  type UpdateChatGroupParams,
  type Message,
  type MessageListParams,
  type MessageStats
} from '@/api/admin'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const chatGroupList = ref<ChatGroup[]>([])

// 搜索表单
const searchForm = reactive<ChatGroupListParams>({
  search: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const announcementDialogVisible = ref(false)
const messagesDialogVisible = ref(false)
const messageDetailDialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const currentChatGroup = ref<ChatGroup | null>(null)
const currentGroupForMessages = ref<ChatGroup | null>(null)
const currentMessageDetail = ref<Message | null>(null)

// 表单
const formRef = ref<FormInstance>()
const formData = reactive<CreateChatGroupParams & { id?: number }>({
  group_name: '',
  group_avatar: '',
  description: ''
})

// 群公告编辑数据
const announcementData = reactive<{ id?: number; description: string; group_name?: string }>({
  description: ''
})

// 消息管理相关数据
const messagesLoading = ref(false)
const messagesList = ref<Message[]>([])
const selectedMessages = ref<Message[]>([])

// 消息搜索表单
const messageSearchForm = reactive<MessageListParams>({
  messageType: undefined,
  search: '',
  senderId: ''
})

// 消息分页
const messagePagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 消息统计
const messageStats = ref<MessageStats>({
  total: 0,
  today: 0,
  byType: {}
})

// 表单验证规则
const formRules = {
  group_name: [
    { required: true, message: '请输入群名称', trigger: 'blur' },
    { min: 1, max: 255, message: '群名称长度在 1 到 255 个字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取群聊列表
const getChatGroupList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    const response = await chatGroupApi.getList(params)
    chatGroupList.value = response.data
    pagination.total = response.pagination.total
  } catch (error: any) {
    console.error('获取群聊列表失败:', error)
    ElMessage.error(error.message || '获取群聊列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getChatGroupList()
}

// 重置搜索
const handleReset = () => {
  searchForm.search = ''
  pagination.page = 1
  getChatGroupList()
}

// 刷新
const handleRefresh = () => {
  getChatGroupList()
}

// 新增群聊
const handleCreate = () => {
  dialogTitle.value = '新增群聊'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑群聊
const handleEdit = (chatGroup: ChatGroup) => {
  dialogTitle.value = '编辑群聊'
  isEdit.value = true
  Object.assign(formData, {
    id: chatGroup.id,
    group_name: chatGroup.group_name,
    group_avatar: chatGroup.group_avatar || '',
    description: chatGroup.description || ''
  })
  dialogVisible.value = true
}

// 查看群聊详情
const handleView = async (chatGroup: ChatGroup) => {
  try {
    const response = await chatGroupApi.getDetail(chatGroup.id)
    currentChatGroup.value = response.data
    detailDialogVisible.value = true
  } catch (error: any) {
    console.error('获取群聊详情失败:', error)
    ElMessage.error(error.message || '获取群聊详情失败')
  }
}

// 编辑群公告
const handleEditAnnouncement = (chatGroup: ChatGroup) => {
  Object.assign(announcementData, {
    id: chatGroup.id,
    group_name: chatGroup.group_name,
    description: chatGroup.description || ''
  })
  announcementDialogVisible.value = true
}

// 删除群聊
const handleDelete = async (chatGroup: ChatGroup) => {
  try {
    await ElMessageBox.confirm(`确定要删除群聊 "${chatGroup.group_name}" 吗？此操作不可恢复！`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await chatGroupApi.delete(chatGroup.id)
    ElMessage.success('群聊删除成功')
    getChatGroupList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除群聊失败:', error)
      ElMessage.error(error.message || '删除群聊失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    if (isEdit.value && formData.id) {
      // 编辑
      const updateData: UpdateChatGroupParams = {
        group_name: formData.group_name,
        group_avatar: formData.group_avatar || undefined,
        description: formData.description || undefined
      }
      await chatGroupApi.update(formData.id, updateData)
      ElMessage.success('群聊更新成功')
    } else {
      // 新增
      const createData: CreateChatGroupParams = {
        group_name: formData.group_name,
        group_avatar: formData.group_avatar || undefined,
        description: formData.description || undefined
      }
      await chatGroupApi.create(createData)
      ElMessage.success('群聊创建成功')
    }

    dialogVisible.value = false
    getChatGroupList()
  } catch (error: any) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    group_name: '',
    group_avatar: '',
    description: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  getChatGroupList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page
  getChatGroupList()
}

// 插入模板内容
const insertTemplate = (template: string) => {
  if (announcementData.description) {
    announcementData.description += '\n\n' + template
  } else {
    announcementData.description = template
  }
}

// 清空公告内容
const clearAnnouncement = () => {
  announcementData.description = ''
}

// 提交群公告
const handleAnnouncementSubmit = async () => {
  if (!announcementData.id) return

  try {
    submitting.value = true

    const updateData: UpdateChatGroupParams = {
      description: announcementData.description || undefined
    }

    await chatGroupApi.update(announcementData.id, updateData)
    ElMessage.success('群公告更新成功')

    announcementDialogVisible.value = false
    getChatGroupList()
  } catch (error: any) {
    console.error('更新群公告失败:', error)
    ElMessage.error(error.message || '更新群公告失败')
  } finally {
    submitting.value = false
  }
}

// 群公告对话框关闭
const handleAnnouncementDialogClose = () => {
  Object.assign(announcementData, {
    id: undefined,
    group_name: undefined,
    description: ''
  })
}

// ==================== 消息管理相关方法 ====================

// 查看群聊消息
const handleViewMessages = async (chatGroup: ChatGroup) => {
  currentGroupForMessages.value = chatGroup
  messagesDialogVisible.value = true

  // 重置数据
  messagesList.value = []
  selectedMessages.value = []
  messageStats.value = { total: 0, today: 0, byType: {} }

  // 重置搜索条件和分页
  Object.assign(messageSearchForm, {
    messageType: undefined,
    search: '',
    senderId: ''
  })
  messagePagination.page = 1
  messagePagination.total = 0

  // 获取消息列表和统计
  await Promise.all([
    getMessagesList(),
    getMessageStats()
  ])
}

// 获取消息列表
const getMessagesList = async () => {
  if (!currentGroupForMessages.value) return

  try {
    messagesLoading.value = true
    const params = {
      page: messagePagination.page,
      pageSize: messagePagination.pageSize,
      ...messageSearchForm
    }

    const response = await messageApi.getGroupMessages(currentGroupForMessages.value.id, params)

    // 确保响应数据结构正确
    if (response.data && response.data.data && Array.isArray(response.data.data)) {
      messagesList.value = response.data.data
    } else {
      messagesList.value = []
      console.warn('API响应数据结构异常:', response)
    }

    if (response.data && response.data.pagination && response.data.pagination.total !== undefined) {
      messagePagination.total = response.data.pagination.total
    } else {
      messagePagination.total = 0
      console.warn('API响应分页信息异常:', response)
    }
  } catch (error: any) {
    console.error('获取消息列表失败:', error)
    ElMessage.error(error.message || '获取消息列表失败')
    messagesList.value = []
    messagePagination.total = 0
  } finally {
    messagesLoading.value = false
  }
}

// 获取消息统计
const getMessageStats = async () => {
  if (!currentGroupForMessages.value) return

  try {
    const response = await messageApi.getGroupStats(currentGroupForMessages.value.id)
    messageStats.value = response.data
  } catch (error: any) {
    console.error('获取消息统计失败:', error)
  }
}

// 消息搜索
const handleMessageSearch = () => {
  messagePagination.page = 1
  getMessagesList()
}

// 重置消息搜索
const handleMessageReset = () => {
  Object.assign(messageSearchForm, {
    messageType: undefined,
    search: '',
    senderId: ''
  })
  messagePagination.page = 1
  getMessagesList()
}

// 刷新消息列表
const handleRefreshMessages = () => {
  Promise.all([
    getMessagesList(),
    getMessageStats()
  ])
}

// 消息选择改变
const handleMessageSelectionChange = (selection: Message[]) => {
  selectedMessages.value = selection
}

// 删除单条消息
const handleDeleteMessage = async (message: Message) => {
  try {
    await ElMessageBox.confirm(`确定要删除这条消息吗？此操作不可恢复！`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await messageApi.delete(message.id)
    ElMessage.success('消息删除成功')

    // 刷新列表和统计
    await Promise.all([
      getMessagesList(),
      getMessageStats()
    ])
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除消息失败:', error)
      ElMessage.error(error.message || '删除消息失败')
    }
  }
}

// 批量删除消息
const handleBatchDeleteMessages = async () => {
  if (selectedMessages.value.length === 0) {
    ElMessage.warning('请选择要删除的消息')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedMessages.value.length} 条消息吗？此操作不可恢复！`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const messageIds = selectedMessages.value.map(msg => msg.id)
    const response = await messageApi.batchDelete({ messageIds })

    ElMessage.success(`成功删除 ${response.data.deletedCount} 条消息`)

    // 清空选择
    selectedMessages.value = []

    // 刷新列表和统计
    await Promise.all([
      getMessagesList(),
      getMessageStats()
    ])
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量删除消息失败:', error)
      ElMessage.error(error.message || '批量删除消息失败')
    }
  }
}

// 消息分页大小改变
const handleMessageSizeChange = (size: number) => {
  messagePagination.pageSize = size
  messagePagination.page = 1
  getMessagesList()
}

// 消息当前页改变
const handleMessageCurrentChange = (page: number) => {
  messagePagination.page = page
  getMessagesList()
}

// 消息对话框关闭
const handleMessagesDialogClose = () => {
  currentGroupForMessages.value = null
  messagesList.value = []
  selectedMessages.value = []
  messageStats.value = { total: 0, today: 0, byType: {} }
}

// 获取消息类型标签类型
const getMessageTypeTagType = (messageType: string) => {
  const typeMap: Record<string, string> = {
    text: '',
    image: 'success',
    system: 'info',
    demand_card: 'warning'
  }
  return typeMap[messageType] || ''
}

// 获取消息类型文本
const getMessageTypeText = (messageType: string) => {
  const typeMap: Record<string, string> = {
    text: '文本',
    image: '图片',
    system: '系统',
    demand_card: '需求卡片'
  }
  return typeMap[messageType] || messageType
}

// ==================== 消息详情相关方法 ====================

// 查看消息详情
const handleViewMessageDetail = (message: Message) => {
  currentMessageDetail.value = message
  messageDetailDialogVisible.value = true
}

// 复制消息内容
const copyMessageContent = async () => {
  if (!currentMessageDetail.value?.content) {
    ElMessage.warning('没有可复制的内容')
    return
  }

  try {
    await navigator.clipboard.writeText(currentMessageDetail.value.content)
    ElMessage.success('消息内容已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请手动复制')
  }
}

// 从详情对话框删除消息
const handleDeleteMessageFromDetail = async () => {
  if (!currentMessageDetail.value) return

  try {
    await ElMessageBox.confirm(`确定要删除这条消息吗？此操作不可恢复！`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await messageApi.delete(currentMessageDetail.value.id)
    ElMessage.success('消息删除成功')

    // 关闭详情对话框
    messageDetailDialogVisible.value = false

    // 刷新列表和统计
    await Promise.all([
      getMessagesList(),
      getMessageStats()
    ])
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除消息失败:', error)
      ElMessage.error(error.message || '删除消息失败')
    }
  }
}

// 消息详情对话框关闭
const handleMessageDetailDialogClose = () => {
  currentMessageDetail.value = null
}

// 初始化
onMounted(() => {
  getChatGroupList()
})
</script>

<style scoped>
.chat-groups-page {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.description-cell {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.chat-group-detail {
  padding: 20px 0;
}

.announcement-content {
  max-height: 100px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-word;
}

.members-section {
  margin-top: 30px;
}

.members-section h4 {
  margin-bottom: 15px;
  color: #303133;
}

.dialog-footer {
  text-align: right;
}

/* 群公告编辑器样式 */
.announcement-editor {
  display: flex;
  gap: 20px;
  min-height: 400px;
}

.editor-section,
.preview-section {
  flex: 1;
}

.editor-section h4,
.preview-section h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.announcement-textarea {
  margin-bottom: 15px;
}

.editor-toolbar {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.announcement-preview {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  min-height: 200px;
  background-color: #fafafa;
}

.preview-content {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
  color: #303133;
}

.preview-placeholder {
  color: #c0c4cc;
  font-style: italic;
  text-align: center;
  padding-top: 80px;
}

/* 消息管理样式 */
.messages-management {
  padding: 0;
}

.search-section,
.stats-section {
  margin-bottom: 20px;
}

.stats-content {
  display: flex;
  gap: 30px;
  align-items: center;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

.stat-value {
  color: #303133;
  font-weight: 600;
  font-size: 16px;
}

.sender-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.sender-details {
  flex: 1;
}

.sender-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 2px;
}

.sender-id {
  font-size: 12px;
  color: #909399;
}

.message-content {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.4;
}

/* 消息详情样式 */
.message-detail {
  padding: 0;
}

.sender-info-detail {
  display: flex;
  align-items: center;
  gap: 12px;
}

.sender-details-detail {
  flex: 1;
}

.sender-details-detail .sender-name {
  font-size: 16px;
  color: #303133;
  margin-bottom: 4px;
  font-weight: 500;
}

.sender-details-detail .sender-id {
  font-size: 12px;
  color: #909399;
  margin-bottom: 2px;
}

.sender-details-detail .sender-phone {
  font-size: 12px;
  color: #606266;
}

.message-content-card {
  margin-top: 20px;
}

.message-content-full {
  max-height: 400px;
  overflow-y: auto;
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 16px;
}

.message-content-full pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  font-size: 14px;
  line-height: 1.6;
  color: #303133;
}
</style>
